package config;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.Data;

/**
 * 全局过滤器
 * @author liujinliang
 */
@Data
public class GlobalFilter implements Filter {

	/** 
	 * 这个变量用来记录 Web 项目的根路径，举个用到的例子吧
	 * <link href="${pageContext.request.contextPath}/css/common.css" rel="stylesheet" type="text/css"/> 
	 */
	private String ctx;
	
	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		/** 设置 request && response 编码格式 UTF-8 */
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		
		req.setCharacterEncoding("UTF-8");
		rep.setCharacterEncoding("UTF-8");
		
		/**
		 * 下面这句代码很重要的哦，我就问你一句话，过滤器过滤掉所有请求之后，
		 * 我们还要不要继续让程序跑了，如果你不希望 DispatcherServlet
		 * 来处理之后的业务逻辑，那你大可以不加下面这句代码，你也不用写代码了
		 */
		chain.doFilter(req, rep);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		this.setCtx(filterConfig.getServletContext().getContextPath());
	}
}
